package com.frxuexi.park2305.notice

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.paging.PagingData
import androidx.paging.filter
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.frxuexi.lib_base.entity.NoticeBeanItem
import com.frxuexi.lib_base.mvi.BaseActivity
import com.frxuexi.lib_base.mvi.UiState
import com.frxuexi.lib_base.utils.ArouterManager
import com.frxuexi.park2305.R
import com.frxuexi.park2305.databinding.ActivityNoticeBinding
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

@Route(path = "/app/NoticeActivity")
@AndroidEntryPoint
class NoticeActivity : BaseActivity<ActivityNoticeBinding,NoticeIntent,NoticeViewModel>() {
    override val binding: ActivityNoticeBinding by lazy { ActivityNoticeBinding.inflate(layoutInflater) }
    override val vm: NoticeViewModel by viewModels<NoticeViewModel>()
    val noticeAdapter by lazy { NoticeAdapter() }

    override fun initData() {
        lifecycleScope.launch {
            vm.uiState.collect{
                when(it){
                    is UiState.onSuccess<*> ->{
                        val data = it.data as PagingData<NoticeBeanItem>
                        noticeAdapter.submitData(data.filter { it.title.isNotEmpty() &&it.content.isNotEmpty() })
                    }

                    else -> {}
                }
            }
        }
    }

    override fun initView() {
        binding.noticeRv.apply {
            adapter=noticeAdapter
            layoutManager=LinearLayoutManager(this@NoticeActivity)
        }

        noticeAdapter.setOnItemClickListener(object :OnItemClickListener{
            override fun onItemClick(item: NoticeBeanItem) {
                ArouterManager.nav(this@NoticeActivity,"/app/NoticedDetailActivity",item.id)
            }

        })

        noticeAdapter.setonItemLongClickListener(object :OnItemLongClickListener{
            override fun onItemLongClik(position: Int): Boolean {
                ToastUtils.showLong(position.toString())
                return true
            }

        })

        binding.headAdd.setOnClickListener {
            ArouterManager.nav(this,"/app/NoticeAddActivity")
        }

    }

    override fun onResume() {
        super.onResume()
        vm.sendIntent(NoticeIntent.getNotices)
    }

}